package net;

import java.io.*;
import java.net.*;

/*
 *  Used to contain the compressed JPEG image data, and send to the UDP server
 *  The previous 40 bytes are store the 10 same values of sizes, since UDP is unreliable, the receiver side should choose the 
 *  frequently appeared value as the correct value of size
 */
public class ImageOutputStream extends OutputStream {
	private int maxSize;
	private int size;
	private byte [] buffer;
	
	public ImageOutputStream(int maxSize){
		this.maxSize = maxSize + 40;
		size = 40;
		buffer = new byte[maxSize];
	}
	
	public int getSize(){
		return size;
	}
	
	@Override
	public void write(int arg0) throws IOException {
		// TODO Auto-generated method stub
		if(size >= maxSize){
			throw new IOException();
		}
		
		buffer[size] = (byte) arg0;
		size++;
	}
	
	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		// TODO Auto-generated method stub
		int i;
		for(i = off;i < off + len;i++){
			this.write((int)b[i]);
		}
	}
	
	@Override
	public void write(byte[] b) throws IOException{
		this.write(b, 0, b.length);
	}
	
	/*
	 *  Send the JPEG image to the UDP server running on another device in a separate thread
	 */
	public void sendImage(final String ip, final int port){
		Thread t = new Thread(){
			public synchronized void run(){
				try {
					// fill the starting 40 bytes with value of size
					int i = 0;
					for(i = 0;i < 10;i++){
						buffer[4 * i + 0] = (byte) size;
						buffer[4 * i + 1] = (byte) (size >>> 8);
						buffer[4 * i + 2] = (byte) (size >>> 16);
						buffer[4 * i + 3] = (byte) (size >>> 24);
					}
					
					// send the packet
					DatagramSocket socket = new DatagramSocket();
					DatagramPacket packet = new DatagramPacket(buffer, size, new InetSocketAddress(ip, port));
					socket.send(packet);
					socket.close();
				} catch (SocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t.start();
	}
}
